import React from "react";
import styles from '@/assets/css/confirm.module.css';
import type RoomType from "@/types/room";
import type GuestType from "@/types/guest";
import type ReceiveType from "@/types/receive";
import type { PickerValue } from 'antd-mobile/es/components/picker-view';

interface OrderInfoType{
    remark: string;
    //价格信息
    origin_price: number|string;
    price: number|string;
    //优惠券
    couponid: number;
    couponstr: string;
    //日期
    datestr: string;
    starttime: number;
    endtime: number;
    //住客
    guest: string;
    gueststr: string;
    guestids: number[];
    //支付方式
    paystr: string;
    pay: string|number;
}

interface CouponPickerProp{
    label:string;
    value:number;
    rate:string;
}

const Confirm = () =>
{
    const [room,SetRoom] = useState<RoomType>({} as RoomType);
    
    // 订单
    const [order,SetOrder] = useState<OrderInfoType>({
        remark: '',
        //价格信息
        origin_price: 0,
        price: 0,
        //优惠券
        couponid: 0,
        couponstr: '暂无优惠券信息',
        //日期
        datestr: '',
        starttime: 0,
        endtime: 0,
        //住客
        guest: '',
        gueststr: '请选择住客信息',
        guestids: [],
        //支付方式
        paystr: '余额支付',
        pay: 'money'
    });

    // 房型id
    const [searchParams] = useSearchParams();
    const [roomid] = useState<string>(searchParams.get('roomid') ?? '');

    // 日期弹出层显示隐藏
    const [DateShow,SetDateShow] = useState<boolean>(false);

    // 日期组件默认日期
    const defaultDateRange: [Date, Date] = [
        new Date(),
        new Date(new Date().getTime() + 86400000),
    ];

    const OnDateConfirm = (values:Date[]|null) =>
    {
        // 条件断言
        if(!values)
        {
            // 更新数据
            SetOrder({
                ...order,
                datestr:'',
                starttime: 0,
                endtime: 0,
            });

            return false;
        }

        // 回显日期格式
        const datestr = `${new Date(values[0]).toLocaleDateString()} - ${new Date(values[1]).toLocaleDateString()}`;

        // 标准时间转换为时间戳
        const starttime = Date.parse(new Date(values[0]).toLocaleDateString()) / 1000;
        const endtime = Date.parse(new Date(values[1]).toLocaleDateString()) / 1000;

        // 更新数据
        SetOrder({
            ...order,
            datestr,
            starttime,
            endtime
        });
    }

    // 住客
    const [GuestShow,SetGuestShow] = useState<boolean>(false);
    const [guest,SetGuest] = useState<GuestType[]>([]);

    const OnGuestChange = (values:number[]) =>
    {
        // 住客的姓名 ['小红','小明']
        const GuestStr:string[] = [];
        // 住客id [1,2] 给后端
        const GuestIds:number[] = [];

        // 循环
        guest.map(item => {
            if(values.includes(item.id))
            {
                GuestStr.push(item.nickname);
                GuestIds.push(item.id);
            }
        });

        // 更新订单数据
        SetOrder({
            ...order,
            gueststr: GuestStr.join('、'),// 小红、小明
            guest: GuestIds.join(','),// 1,2
            guestids:GuestIds,
        });
    }

    // 优惠券
    const [CouponShow,SetCouponShow] = useState<boolean>(false);
    const [coupon,SetCoupon] = useState<CouponPickerProp[][]>([[]]);

    const OnCouponChange = (values:number[]) =>
    {
        let couponstr:string = '';

        if(!values[0])
        {
            return false;
        }

        // 获取picker第一个选项
        const list:CouponPickerProp[] = coupon[0];

        // 循环遍历
        list.map((item) => {
            if(item.value == values[0])
            {
                couponstr = item.label;
            }
        });

        //设置订单数据
        SetOrder({
            ...order,
            couponstr,
            couponid: values[0]
        });
    }

    // 支付方式
    const [PayList] = useState([[
        { label: '余额支付', value: 'money' },
        { label: '微信支付', value: 'wx' },
        { label: '支付宝支付', value: 'zfb' },
    ]]);
    const [PayShow,SetPayShow] = useState<boolean>(false);

    const OnPayChange = (values:PickerValue[]) =>
    {
        let PayStr:string = '余额支付';

        PayList[0].map(item =>
        {
            if(values.includes(item.value))
            {
                PayStr = item.label;
            }
        });

        SetOrder({
            ...order,
            paystr: PayStr,
            pay: values[0] ? values[0] : 'money'
        })
    }

    // 价格
    const [OriginPrice,SetOriginPrice] = useState<number>(0);
    const [price,SetPrice] = useState<number>(0);

    // 天数
    const [day,SetDay] = useState<number>(0);

    useEffect(() => {
        Total();
    },[order,roomid]);

    // vue 的 computed
    const Total = () =>
    {
        // 从 order 获取开始入住时间和退房时间
        const starttime = order.starttime;
        const endtime = order.endtime;

        // 时间差
        const durationSeconds = endtime - starttime;

        // 计算预定多少天 86400 = 60 * 60 * 24
        const day = Math.floor(durationSeconds / 86400);

        // 转换单位
        const truncateToTwoDecimals = (num: number) => Math.trunc(num * 100) / 100;

        // 原价 = 时间差 * 房间原价
        const origin_price = truncateToTwoDecimals(parseFloat(room.price) * day);
        let price = origin_price;

        //如果用户是有选择优惠券
        if(order.couponid)
        {
            // 找出当前选中优惠券的记录
            let CouponActive:CouponPickerProp|undefined = {
                label:'',
                value:0,
                rate:'1'
            };

            // 条件断言 如果是有优惠数据并且用户选了用优惠券预订
            if(coupon[0].length > 0)
            {
                // 根据用户选中的优惠券领取id找出是哪张优惠券
                CouponActive = coupon[0].find((item:CouponPickerProp) => item.value == order.couponid);
            }

            // 条件断言
            if(CouponActive && CouponActive.value > 0)
            {
                // 优惠券使用后的实际的价格
                price = truncateToTwoDecimals(price * parseFloat(CouponActive.rate))
            }
        }

        SetDay(day);
        SetPrice(price);
        SetOriginPrice(origin_price);
    }

    // 确认提交订单
    const OnOrderConfirm = async () =>
    {
        // 添加预订订单的数据参数
        const params = {
            roomid,
            busid:React.business.id,
            starttime:order.starttime,
            endtime:order.endtime,
            guestids:order.guest,
            couponid:order.couponid,
            remark:order.remark
        }

        // 支付方式有三种，如果用户选择余额支付
        if(order.pay === 'money')
        {
            // 实现余额支付的逻辑
            const result = await React.http.post('/order/add',params);

            if(result.code === 1)
            {
                React.success(result.msg,() =>
                {
                    React.navigate(result.url,{replace:true});
                });
            }else{
                React.fail(result.msg);
            }
        }else{
            // 实现微信或者支付宝支付的逻辑
        }

    }

    // 订单备注事件
    const OnRemarkChange = (value:string) =>
    {
        SetOrder({
            ...order,
            remark:value
        })
    }

    // 计算总价
    const OrderPrice = () =>
    {
        if(price == OriginPrice)
        {
            return (
                <div className={styles.text}>
                    <span>总价:</span>
                    <span>￥{price}</span>
                </div>
            )
        }else
        {
            return (
                <div className={styles.text}>
                    <span>优惠价格:</span>
                    <span>￥{price}</span>
                    <s>原价：￥{OriginPrice}</s>
                </div>
            )
        }
    }

    // 数据请求
    useEffect(() =>
    {
        GetConfirmData();
    },[]);

    // 获取确认订单
    const GetConfirmData = async () =>
    {
        const params = {
            roomid,
            busid:React.business.id
        }

        const result = await React.http.post('/room/confirm',params);

        if(result.code === 1)
        {
            SetRoom(result.data.room);

            const CouponData:CouponPickerProp[] = [];

            // 初始化时间
            // `现在时间 - 第二天时间`
            const datestr = `${new Date(defaultDateRange[0]).toLocaleDateString()} - ${new Date(defaultDateRange[1]).toLocaleDateString()}`;

            // 标准时间转换为时间戳
            const starttime = Date.parse(new Date(defaultDateRange[0]).toLocaleDateString()) / 1000;
            const endtime = Date.parse(new Date(defaultDateRange[1]).toLocaleDateString()) / 1000;

            const info:OrderInfoType = {
                ...order,
                datestr,
                starttime,
                endtime
            }

            if(result.data.CouponList.length > 0)
            {
                result.data.CouponList.map((item:ReceiveType) => {
                    CouponData.push({
                        label: `${item.coupon.title}-${parseFloat(item.coupon.rate) * 10}折`,
                        value: item.id,
                        rate: item.coupon.rate
                    })
                });

                info.couponstr = `有${CouponData.length}张可用优惠券`;
            }else{
                CouponData.push({
                    label: `暂无优惠券信息`,
                    value: 0,
                    rate: '1'
                });
            }

            SetCoupon([CouponData]);

            SetGuest(result.data.GuestList);

            SetOrder({
                ...info
            })

        }else{
            React.fail(result.msg,() => {
                React.navigate(-1);
            });
        }
    }

    return (
        <>
            <div className={styles.skeleton}>
                {/* 房间信息 */}
                <div className={styles.detail}>
                    <div className={styles.thumb}>
                        <img src={room.thumb_text} alt="" />
                    </div>
                    <div className={styles.right}>
                        <p>{room.name}</p>
                        <p>￥{room.price} / 晚</p>
                        <div className={styles.tips}>
                            {room.flag && room.flag_text.map((flag: string, index: number) => <span key={index}> {flag} </span>)}
                        </div>
                    </div>
                </div>

                {/* 入住时间 */}
                <div className={styles.skeleton_rect}>
                    <div className={styles.item}>
                        <label>入住日期</label>
                        <React.UI.Input type="text" className={styles.item_right} placeholder="请选择入住日期" value={order.datestr} onClick={() => SetDateShow(true)} />
                    </div>

                    {/* 日期选择 */}
                    <React.UI.CalendarPicker
                        visible={DateShow}
                        min={new Date()}
                        defaultValue={defaultDateRange}
                        selectionMode='range'
                        onClose={() => SetDateShow(false)}
                        onMaskClick={() => SetDateShow(false)}
                        onConfirm={OnDateConfirm}

                    >
                    </React.UI.CalendarPicker>

                    {/* 住客信息 */}
                    <div className={styles.item}>
                        <label>住客信息</label>
                        <div className={order.guestids.length > 0 ? styles.item_right : styles.item_rights} onClick={() => SetGuestShow(true)}>{order.gueststr}</div>
                    </div>

                    {/* 弹出层 */}
                    <React.UI.Popup
                        visible={GuestShow}
                        destroyOnClose
                        onMaskClick={() => SetGuestShow(false)}
                        style={{borderRadius: '10px'}}
                    >
                        <React.UI.CheckList
                            multiple
                            defaultValue={order.guestids}
                            onChange={OnGuestChange}
                            style={{height: '55vh',overflowY: 'scroll'}}
                        >
                            {guest && guest.map((item:GuestType, key:number) => (
                                <React.UI.CheckList.Item key={key} value={item.id}>
                                    {item.nickname}（{item.mobile}）
                                </React.UI.CheckList.Item>
                            ))}
                        </React.UI.CheckList>

                        <React.UI.Button color="primary" block style={{ width: '100%' }} onClick={() => SetGuestShow(false)}>确认</React.UI.Button>
                    </React.UI.Popup>



                </div>

                {/* 优惠券 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>优惠券</div>
                    <p>{order.couponstr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetCouponShow(true)}>选择</React.UI.Button>

                    {/* 弹框选项 */}
                    <React.UI.Picker
                        visible={CouponShow}
                        columns={coupon}
                        onClose={() => SetCouponShow(false)}
                        onConfirm={OnCouponChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 支付方式 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>支付方式</div>
                    <p>{order.paystr}</p>
                    <React.UI.Button size="mini" color="primary" onClick={() => SetPayShow(true)}>选择</React.UI.Button>

                    <React.UI.Picker
                        columns={PayList}
                        visible={PayShow}
                        onClose={() => SetPayShow(false)}
                        onConfirm={OnPayChange}
                    >
                    </React.UI.Picker>
                </div>

                {/* 订单备注 */}
                <div className={styles.skeleton_price} style={{alignItems:'unset'}}>
                    <div className={styles.tips}>订单备注</div>
                    <React.UI.TextArea placeholder={'请输入订单备注'} rows={2} value={order.remark} onChange={OnRemarkChange} />
                </div>

                {/* 费用 */}
                <div className={styles.skeleton_price}>
                    <div className={styles.tips}>房间费用</div>
                    <div className={styles.prices}>
                        <span>￥{OriginPrice}</span>
                        <span>共 {day} 晚</span>
                    </div>
                </div>


            </div>

            <div className={styles.comfirm_foot_bar}>
                <OrderPrice />
                <React.UI.Button onClick={OnOrderConfirm} color='primary' size={'small'}>提交订单</React.UI.Button>
            </div>
        </>
    )
}

export default Confirm;